package com.istock.monitor.agent.transformer;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class TransformerFactory implements ClassFileTransformer {

	private ClassRewriterRegistry registry;
	
	public TransformerFactory(ClassRewriterRegistry registry){
		this.registry = registry;
	}
	
	@Override
	public byte[] transform(ClassLoader loader, String className,Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) throws IllegalClassFormatException {
		
		ClassRewriter rewriter = registry.findRewriter(className);
		if(rewriter != null){
			System.out.println("======transform======="+className);
			byte[] classByte = rewriter.rewriteClass(classfileBuffer);
//			ClassUtils.outputClass(className, classByte);
			return classByte;
		}
		return classfileBuffer;
	}

	/*private boolean needProxy(String className){
		boolean result = false;
		for(String classRegx : includeList){
			if(className.matches(classRegx)){
				return true;
			}
		}
		
		boolean inConfigInclude = false;
		for(String classRegx : config.getInclude()){
			if(className.matches(classRegx)){
				inConfigInclude = true;
				break;
			}
		}
		
		if(inConfigInclude){
			boolean inConfigExclude = false;
			for(String classRegx : config.getExclude()){
				if(className.matches(classRegx)){
					inConfigExclude = true;
					break;
				}
			}
			return inConfigInclude && !inConfigExclude;
		}
		
		return result;
	}*/
}
